package dp.mobile.eden;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;

import dp.mobile.comm.ICommHandler;
import dp.mobile.comm.worker.BluetoothHandler;
import dp.mobile.eden.multiplayer.message.MessageBase;
import dp.mobile.eden.multiplayer.message.ReadyUpdate;
import dp.mobile.system.SoundManager;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class InitiateMultiplayerAct extends Activity implements ICommHandler {
	private Button mStartServerButton , mFindServerButton , mStartGameButton;
	private boolean isServer = false;
	private boolean isGamePlayed = false;
	private final int mObjectId = 100;
	
	private static final int ENABLE_BT_REQUEST = 3;
	private static final int ENABLE_DISCOVERABILITY = 4;
	private static final int DISCOVER_DEVICE = 5;
	
	private final static int MSG_WHAT_CONNECTED = 1000;
	private final static int MSG_WHAT_OBJECT_RECEIVED = 1;
	public final static String EXTRA_PROP_DELAY = "PROP_DELAY";
	public final static String EXTRA_IS_SERVER = "ACTIVITY_ROLE";
	
	//private long mStartCalibration/* , mPropDelay*/;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.initiate_multiplayer);
		
		BluetoothHandler handler = BluetoothHandler.getInstance();
        handler.reset();
        if (handler.getAdapter().isEnabled()) {
        	Log.i("this" , "Bluetooth started");
        }
        else {
        	Log.i("this" , "Bluetooth not started");
        	Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent , ENABLE_BT_REQUEST);
        }
        
        handler.setEventHandler(this);
        init();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.i("this" , "REQ CODE : " + requestCode);
		if (requestCode == ENABLE_BT_REQUEST) {
			if (resultCode != RESULT_OK) {
				finish();
			}
		}
		else if (requestCode == ENABLE_DISCOVERABILITY) {
			if (resultCode == 300) {
				isServer = true;
				BluetoothHandler.getInstance().startServer();
		        mStartServerButton.setEnabled(false);
		        mStartServerButton.setText("Waiting...");
		        mFindServerButton.setVisibility(View.GONE);
			}
		}
		else if (requestCode == DISCOVER_DEVICE) {
			if (resultCode == RESULT_OK) {
				//doPlayGame();
			}
		}
	}
	
	private void init() {
		mStartGameButton = (Button) findViewById(R.id.start_game_btn);
		mStartGameButton.setVisibility(View.GONE);
		
		mStartGameButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				ReadyUpdate m = new ReadyUpdate(0);
				BluetoothHandler.getInstance().sendObjectId(mObjectId);
				BluetoothHandler.getInstance().send(m);
				//mStartCalibration = System.currentTimeMillis();
				//doPlayGame();
			}
		});
		
		mStartServerButton = (Button) findViewById(R.id.start_server_btn);
		mStartServerButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
		        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
		        startActivityForResult(discoverableIntent, ENABLE_DISCOVERABILITY);
			}
		});
		
		mFindServerButton = (Button) findViewById(R.id.find_server_btn);
		mFindServerButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				discover();
			}
		});
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		BluetoothHandler.getInstance().setEventHandler(this);
		
		if (isGamePlayed) {
			startActivity(new Intent(this.getApplicationContext() , InitiateMultiplayerAct.class));
			finish();
		}
		else if (BluetoothHandler.getInstance().getConnectedDevice() != null) {
			doPlayGame();
		}
		
		SoundManager.instance(getBaseContext()).temporarySetMute(false);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		SoundManager.instance(getBaseContext()).temporarySetMute(true);
	}
	
	private void discover() {
		startActivityForResult(new Intent(this.getApplicationContext() , DeviceListAct.class) , DISCOVER_DEVICE);
	}
	
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Log.i("this" , "MSG WHAT : " + msg.what + "");
			if (msg.what == MSG_WHAT_CONNECTED) {
				if (isServer)
					doPlayGame();
			}
			else if (msg.what == MSG_WHAT_OBJECT_RECEIVED) {
				if (mIncomingMessage.getId() == MessageBase.ID_READY_UPDATE) {
					if (!isServer) {
						mFindServerButton.setText("Server OK");
						ReadyUpdate m = new ReadyUpdate(0);
						BluetoothHandler.getInstance().sendObjectId(mObjectId);
						BluetoothHandler.getInstance().send(m);
						doPlayGame();
					}
					else {
						doPlayGame();
					}
				}
			}
		}
	};
	
	private void doPlayGame() {
		isGamePlayed = true;
		Intent i = new Intent(this.getApplicationContext(), MultiplayerAct.class);
		i.putExtra(EXTRA_IS_SERVER, isServer);
		startActivity(i);	
	}

	public void onAcceptFailed() {}

	public void onConnectFailed() {}

	public void onConnected() {
		Message m = new Message();
		m.what = MSG_WHAT_CONNECTED;
		mHandler.sendMessage(m);
	}

	private MessageBase mIncomingMessage;
	
	public void onObjectReceived(int objId, ObjectInputStream ois) {
		Log.i("this" , String.valueOf(objId));
		if (objId == mObjectId) {
			try {
				mIncomingMessage = (MessageBase)ois.readObject();
				Message m = new Message();
				m.what = MSG_WHAT_OBJECT_RECEIVED;
				mHandler.sendMessage(m);
			} catch (StreamCorruptedException e) {e.printStackTrace();
			} catch (IOException e) {e.printStackTrace();
			} catch (ClassNotFoundException e) {e.printStackTrace();}
		}
	}

	public void onConnectionFailed() {}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		BluetoothHandler.getInstance().reset();
	}
}
